<script setup lang="ts">
import { ref } from 'vue';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'select',customer: any): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 搜索表单
const searchForm = ref({
  petName: '',
  ownerName: '',
  phone: '',
});

// 当前激活的标签页
const activeTab = ref('pets');

// 搜索结果
const petResults = ref<any[]>([]);
const customerResults = ref<any[]>([]);

// 详情模态框
const detailModal = ref({
  visible: false,
  title: '',
  type: '',
  data: null as any,
});

// 宠物表格列定义
const petColumns = [
  {
    title: '宠物名称',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '类型',
    dataIndex: 'petType',
    key: 'petType',
    width: 100,
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed',
    width: 120,
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 80,
  },
  {
    title: '主人',
    dataIndex: 'ownerName',
    key: 'ownerName',
    width: 100,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 主人表格列定义
const customerColumns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80,
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 80,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 模拟宠物数据
const mockPets = [
  {
    id: 'P001',
    name: '小白',
    petType: 'dog',
    breed: '金毛',
    age: 3,
    gender: 'male',
    weight: 25,
    ownerName: '张三',
    phone: '13800138001',
    address: '北京市朝阳区xxx街道',
    notes: '定期体检',
  },
  {
    id: 'P002',
    name: '咪咪',
    petType: 'cat',
    breed: '英短',
    age: 2,
    gender: 'female',
    weight: 4,
    ownerName: '李四',
    phone: '13800138002',
    address: '北京市海淀区xxx街道',
    notes: '已绝育',
  },
  {
    id: 'P003',
    name: '旺财',
    petType: 'dog',
    breed: '拉布拉多',
    age: 1,
    gender: 'male',
    weight: 20,
    ownerName: '王五',
    phone: '13800138003',
    address: '北京市西城区xxx街道',
    notes: '幼犬',
  },
];

// 模拟主人数据
const mockCustomers = [
  {
    id: 'C001',
    name: '张三',
    gender: 'male',
    age: 30,
    phone: '13800138001',
    address: '北京市朝阳区xxx街道',
    notes: '养狗经验丰富',
  },
  {
    id: 'C002',
    name: '李四',
    gender: 'female',
    age: 28,
    phone: '13800138002',
    address: '北京市海淀区xxx街道',
    notes: '新手养猫',
  },
  {
    id: 'C003',
    name: '王五',
    gender: 'male',
    age: 35,
    phone: '13800138003',
    address: '北京市西城区xxx街道',
    notes: '多只宠物',
  },
];

// 方法
const getPetTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    dog: 'blue',
    cat: 'orange',
    bird: 'green',
    rabbit: 'pink',
    other: 'default',
  };
  return colorMap[type] || 'default';
};

const getPetTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    dog: '狗狗',
    cat: '猫咪',
    bird: '鸟类',
    rabbit: '兔子',
    other: '其他',
  };
  return textMap[type] || type;
};

// 搜索方法
const searchPets = () => {
  if (
    !searchForm.value.petName &&
    !searchForm.value.ownerName &&
    !searchForm.value.phone
  ) {
    message.warning('请输入搜索条件');
    return;
  }

  // 模拟搜索逻辑
  let results = mockPets;

  if (searchForm.value.petName) {
    results = results.filter(
      (pet) =>
        pet.name
          .toLowerCase()
          .includes(searchForm.value.petName.toLowerCase()) ||
        pet.id.toLowerCase().includes(searchForm.value.petName.toLowerCase()),
    );
  }

  if (searchForm.value.ownerName) {
    results = results.filter((pet) =>
      pet.ownerName
        .toLowerCase()
        .includes(searchForm.value.ownerName.toLowerCase()),
    );
  }

  if (searchForm.value.phone) {
    results = results.filter((pet) =>
      pet.phone.includes(searchForm.value.phone),
    );
  }

  petResults.value = results;
  activeTab.value = 'pets';
  message.success(`找到 ${results.length} 条宠物记录`);
};

const searchCustomers = () => {
  if (!searchForm.value.ownerName && !searchForm.value.phone) {
    message.warning('请输入搜索条件');
    return;
  }

  let results = mockCustomers;

  if (searchForm.value.ownerName) {
    results = results.filter((customer) =>
      customer.name
        .toLowerCase()
        .includes(searchForm.value.ownerName.toLowerCase()),
    );
  }

  if (searchForm.value.phone) {
    results = results.filter((customer) =>
      customer.phone.includes(searchForm.value.phone),
    );
  }

  customerResults.value = results;
  activeTab.value = 'customers';
  message.success(`找到 ${results.length} 条主人记录`);
};

const searchByPhone = () => {
  if (!searchForm.value.phone) {
    message.warning('请输入手机号');
    return;
  }

  const petResults = mockPets.filter((pet) =>
    pet.phone.includes(searchForm.value.phone),
  );
  const customerResults = mockCustomers.filter((customer) =>
    customer.phone.includes(searchForm.value.phone),
  );

  petResults.value = petResults;
  customerResults.value = customerResults;
  activeTab.value = 'pets';
  message.success(
    `找到 ${petResults.length} 条宠物记录，${customerResults.length} 条主人记录`,
  );
};

const clearSearch = () => {
  searchForm.value = {
    petName: '',
    ownerName: '',
    phone: '',
  };
  petResults.value = [];
  customerResults.value = [];
};

// 详情查看
const viewPetDetails = (pet: any) => {
  detailModal.value = {
    visible: true,
    title: `宠物详情 - ${pet.name}`,
    type: 'pet',
    data: pet,
  };
};

const viewCustomerDetails = (customer: any) => {
  detailModal.value = {
    visible: true,
    title: `主人详情 - ${customer.name}`,
    type: 'customer',
    data: customer,
  };
};

const closeDetailModal = () => {
  detailModal.value.visible = false;
};

// 选择
const selectPet = (pet: any) => {
  emit('select', {
    type: 'pet',
    data: pet,
  });
  emit('update:visible', false);
};

const selectCustomer = (customer: any) => {
  emit('select', {
    type: 'customer',
    data: customer,
  });
  emit('update:visible', false);
};

const handleCancel = () => {
  emit('update:visible', false);
  clearSearch();
};
</script>

<template>
  <a-modal
    :open="visible"
    title="🔍 顾客查询"
    width="1000px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="customer-search">
      <!-- 搜索区域 -->
      <div class="search-section">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="宠物名称/编号">
              <a-input
                v-model:value="searchForm.petName"
                placeholder="输入宠物名称或编号"
                @keyup.enter="searchPets"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="主人姓名">
              <a-input
                v-model:value="searchForm.ownerName"
                placeholder="输入主人姓名"
                @keyup.enter="searchCustomers"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="手机号">
              <a-input
                v-model:value="searchForm.phone"
                placeholder="输入手机号"
                @keyup.enter="searchByPhone"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-space>
              <a-button type="primary" @click="searchPets">查询宠物</a-button>
              <a-button @click="searchCustomers">查询主人</a-button>
              <a-button @click="searchByPhone">按手机号查询</a-button>
              <a-button @click="clearSearch">清空</a-button>
            </a-space>
          </a-col>
        </a-row>
      </div>

      <!-- 搜索结果 -->
      <div class="search-results">
        <a-tabs v-model:active-key="activeTab">
          <a-tab-pane key="pets" tab="宠物信息">
            <a-table
              :columns="petColumns"
              :data-source="petResults"
              :pagination="{ pageSize: 5 }"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'petType'">
                  <a-tag :color="getPetTypeColor(record.petType)">
                    {{ getPetTypeText(record.petType) }}
                  </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="viewPetDetails(record)"
                    >
                      查看详情
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="selectPet(record)"
                    >
                      选择
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="customers" tab="主人信息">
            <a-table
              :columns="customerColumns"
              :data-source="customerResults"
              :pagination="{ pageSize: 5 }"
              size="small"
              row-key="id"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="viewCustomerDetails(record)"
                    >
                      查看详情
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="selectCustomer(record)"
                    >
                      选择
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- 详细信息模态框 -->
      <a-modal
        :open="detailModal.visible"
        :title="detailModal.title"
        width="600px"
        @cancel="closeDetailModal"
        :footer="null"
      >
        <div v-if="detailModal.data" class="detail-content">
          <a-descriptions :column="2" bordered>
            <template v-if="detailModal.type === 'pet'">
              <a-descriptions-item label="宠物名称">
                {{ detailModal.data.name }}
              </a-descriptions-item>
              <a-descriptions-item label="宠物类型">
                {{ getPetTypeText(detailModal.data.petType) }}
              </a-descriptions-item>
              <a-descriptions-item label="品种">
                {{ detailModal.data.breed }}
              </a-descriptions-item>
              <a-descriptions-item label="年龄">
                {{ detailModal.data.age }}岁
              </a-descriptions-item>
              <a-descriptions-item label="性别">
                {{ detailModal.data.gender === 'male' ? '公' : '母' }}
              </a-descriptions-item>
              <a-descriptions-item label="体重">
                {{ detailModal.data.weight }}kg
              </a-descriptions-item>
              <a-descriptions-item label="主人姓名">
                {{ detailModal.data.ownerName }}
              </a-descriptions-item>
              <a-descriptions-item label="联系电话">
                {{ detailModal.data.phone }}
              </a-descriptions-item>
              <a-descriptions-item label="地址" :span="2">
                {{ detailModal.data.address }}
              </a-descriptions-item>
              <a-descriptions-item label="备注" :span="2">
                {{ detailModal.data.notes || '无' }}
              </a-descriptions-item>
            </template>
            <template v-else>
              <a-descriptions-item label="姓名">
                {{ detailModal.data.name }}
              </a-descriptions-item>
              <a-descriptions-item label="性别">
                {{ detailModal.data.gender === 'male' ? '男' : '女' }}
              </a-descriptions-item>
              <a-descriptions-item label="手机号">
                {{ detailModal.data.phone }}
              </a-descriptions-item>
              <a-descriptions-item label="年龄">
                {{ detailModal.data.age }}岁
              </a-descriptions-item>
              <a-descriptions-item label="地址" :span="2">
                {{ detailModal.data.address }}
              </a-descriptions-item>
              <a-descriptions-item label="备注" :span="2">
                {{ detailModal.data.notes || '无' }}
              </a-descriptions-item>
            </template>
          </a-descriptions>
        </div>
      </a-modal>
    </div>
  </a-modal>
</template>

<style scoped>
.customer-search {
  max-height: 600px;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
}

.search-results {
  margin-top: 16px;
}

.detail-content {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>
